package com.applications.codemash.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.applications.codemash.utility.CustomContext;
import com.applications.codemash.utility.exceptions.RecordNotFoundException;
import com.applications.codemash.utility.parser.SessionFeedParser;

public class SessionCollection extends ArrayList<Session>
{
	private static final long serialVersionUID = -557482935792298052L;
	
	private SessionCollection()
	{
		
	}
	
	public static SessionCollection GetAllSessions() throws Exception
	{
		SessionFeedParser sessionParser = new SessionFeedParser(Constants.GetAllSessionsUri());
		List<Session> sessionList = sessionParser.parse();
		SessionCollection list = new SessionCollection();
		
		Date codeMashStartDate = new Date(110, 0, 13, 0, 0, 0);
		Date codeMashEndDate = new Date(110, 0, 15, 23, 59, 59);
		
		for (int i=0; i<sessionList.size(); i++)
		{
			Session session = sessionList.get(i);
			Date sessionStartDate = session.getStart();
			
			if (sessionStartDate.before(codeMashEndDate) && sessionStartDate.after(codeMashStartDate))
			{
				try
				{
					boolean value = CustomContext.getDbAdapter().GetActiveStateForSession(session.getSessionUri());
					session.setNotifyOnStart(value);
				}
				catch (RecordNotFoundException recordEx)
				{
					CustomContext.getDbAdapter().AddSession(session.getSessionUri(), false);
					session.setNotifyOnStart(false);
				}
				session.setNotificationId(i + 1000);
				list.add(session);
			}
		}

		if (list.size() == 0) throw new Exception("List Count cannot be zero");
		return list;
	}
	
	public Session GetSessionBySessionUri(String uri)
	{
		for (Session session : this)
		{
			if (session.getSessionUri().compareToIgnoreCase(uri) == 0)
			{
				return session;
			}
		}
		
		// TODO: enable this to be loaded from the service URL and placed into our collection
		return null;
	}
	
	public List<Session> GetSessionsForSpeaker(String speakerUri)
	{
		List<Session> list = new ArrayList<Session>();
		
		for (Session session : this)
		{
			if (session.getSpeakerUri().compareToIgnoreCase(speakerUri) == 0)
			{
				list.add(session);
			}
		}
		
		return list;
	}
	
	public List<Session> GetSessionsForTrack(String track)
	{
		List<Session> list = new ArrayList<Session>();
		
		for (Session session : this)
		{
			if (session.getTrack().compareToIgnoreCase(track) == 0)
			{
				list.add(session);
			}
		}
		
		Collections.sort(list);
		return list;
	}
}
